﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace HBattle
{
    public class MessageDispatcher : SingletonManager<MessageDispatcher>
    {
        public class TelegramComparer : IComparer<Telegram>
        {
            public int Compare(Telegram x, Telegram y)
            {
                if (x.DispatchTime > y.DispatchTime)
                {
                    return 1;
                }
                else if (x.DispatchTime < y.DispatchTime)
                {
                    return -1;
                }
                return 0;
            }
        }

        private PriorityQueue<Telegram> priorityQ = new PriorityQueue<Telegram>(new TelegramComparer());

        private void Discharge(BaseGameEntity receiver, Telegram msg)
        {
            if (!receiver.HandleMessage(msg))
            {
                Debug.LogWarning("Message not handled");
            }
        }

        public void DispatchMessage(float delay, int sender, int receiver, MSG msg, System.Object extraInfo)
        {
            BaseGameEntity receiverEntity = EntityManager.Instance.GetEntityFromID(receiver);
            if (receiverEntity == null)
            {
                Debug.LogWarning("Warning! No Receiver with ID of " + receiver + "found");
            }

            Telegram t = new Telegram(sender, receiver, msg, 0, extraInfo);

            if (delay <= 0.0f)
            {
                Discharge(receiverEntity, t);
            }
            else
            {
                float currentTime = Time.time;
                t.DispatchTime = currentTime + delay;
                priorityQ.Push(t);

            }
        }

        public void DispatchDelayedMessages()
        {
            float currentTime = Time.time;

            while(priorityQ.Count > 0 && priorityQ.Top().DispatchTime < currentTime && priorityQ.Top().DispatchTime > 0)
            {
                Telegram t = priorityQ.Top();
                BaseGameEntity receiverEntity = EntityManager.Instance.GetEntityFromID(t.Receiver);
                Discharge(receiverEntity, t);
                priorityQ.Pop();
            }

        }

    }
}
